<template>
    <div class="index-edit">
        <!-- 编辑弹窗 -->
        <cvue-dialog :dialogVisible="dialogVisible"
            :dialogLoading="dialogLoading"
            title="编辑"
            dialogWidth="600px"
            @handleOpen="getDetail"
            @closeDialog="closeDialog"
            @confirmDialog="confirmDialog"
            @handleClose="handleClose">
            <div class="dialog-body" slot="dialogBody">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="用户名" prop="userName">
                                <el-input v-model.trim="ruleForm.userName"  disabled placeholder="请输入用户名"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="姓名" prop="name">
                                <el-input maxlength="10" placeholder="请输入姓名，2-10个字符" v-model.trim="ruleForm.name"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="联系电话" prop="phone">
                                <el-input maxlength="11" v-model.trim="ruleForm.phone" placeholder="请输入联系电话"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="管辖代理" prop="tjrId">
                                <el-cascader :options="austUser" :props="optionProps" v-model.trim="ruleForm.underCustId" :show-all-levels="false" filterable>
                                </el-cascader>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="角色" prop="roleId">
                                <el-select placeholder="请选择" v-model="ruleForm.roleId" class="select-width" @change="selectRole">
                                    <el-option v-for="item in roleType" :key="item.roleId" :label="item.roleName" :value="item.roleId"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="状态" prop="state">
                                <el-radio-group v-model="ruleForm.state">
                                    <el-radio :label="1">启用</el-radio>
                                    <el-radio :label="0">禁用</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="页面权限" prop="authority">
                                <cvue-tree-grid :option="option">
                                    <template slot-scope="scope" slot="edit">
                                        <template v-if="scope.row.code == 20010 || scope.row.code == 20020">
                                            <el-checkbox disabled></el-checkbox>
                                        </template>
                                        <template v-else>
                                            <el-checkbox v-model="scope.row.edit" v-if="checkScope(scope.row)" @change="editChange(scope.row)"></el-checkbox>
                                        </template>
                                    </template>
                                    <template slot-scope="scope" slot="view">
                                        <template>
                                            <el-checkbox v-model="scope.row.view" v-if="checkScope(scope.row)" @change="viewChange(scope.row)"></el-checkbox>
                                        </template>
                                    </template>
                                </cvue-tree-grid>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </cvue-dialog>
    </div>
</template>
<script>
import cvueTreeGrid from '@/components/cvue-tree-grid'
import cvueDialog from '@/components/cvue-dialog'
import cvueTable from '@/components/cvue-table'
import {validPhone, validIp} from '@/util/validator.js'
export default {
    name: 'indexEdit',
    components: {
        cvueDialog,
        cvueTable,
        cvueTreeGrid
    },
    data () {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'))
            } else {
                if (this.ruleForm.checkPassword !== '') {
                    this.$refs.ruleForm.validateField('checkPassword')
                }
                callback()
            }
        }
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.ruleForm.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        return {
            austUser: [],
            ruleForm: {
                userName: '',
                name: '',
                phone: '',
                roleId: '',
                state: '',
                password: '',
                checkPassword: '',
                underCustId: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, trigger: 'blur', validator: validPhone }
                ],
                password: [
                    { required: true, validator: validatePass, trigger: 'blur' }
                ],
                checkPassword: [
                    { required: true, validator: validatePass2, trigger: 'blur' }
                ]
            },
            optionProps: {
                value: 'id',
                label: 'label',
                children: 'children',
                checkStrictly: true,
                emitPath: false
            },
            disabled: true,
            dialogLoading: false,
            tableOption: {
                stripe: true,
                width: '100%',
                border: true,
                index: false,
                cloumn: [
                    {prop: 'describe', label: '模块', align: 'center'},
                    {prop: 'edit', label: '编辑权限', align: 'center', slotStatus: true},
                    {prop: 'view', label: '查看权限', align: 'center', slotStatus: true}
                ]
            },
            tableData: [
                {
                  code: '运营报表', edit: false, view: true
                }
            ],
            roleType: [
            ],
            option: {
                expandAll: true,
                columns: [
                    {
                        text: '模块',
                        value: 'describe',
                        width: 200
                    },
                    {
                        text: '编辑权限',
                        value: 'edit',
                        slotStatus: true,
                        align: 'center'
                    },
                    {
                        text: '查看权限',
                        value: 'view',
                        slotStatus: true,
                        align: 'center'
                    }
                ],
                data: [
                ]
            }
        }
    },
    props: {
        dialogVisible: {
            type: Boolean,
            default: false
        }
    },
    mounted () {
    },
    methods: {
        getUnderAgentUser() {
            this.$store.dispatch('agent/GetAgentUserList').then((res) => {
                if (res.code === 200) {
                this.austUser = this.getTreeData(res.data)
                }
            })
        },
        getTreeData(data) {
			for (var i = 0; i < data.length; i++) {
				if (data[i].children.length < 1) {
					// children若为空数组，则将children设为undefined
					data[i].children = undefined
				} else {
					// children若不为空数组，则继续 递归调用 本方法
					this.getTreeData(data[i].children)
				}
			}
			return data
		},
        // 角色选择
        selectRole (roleId) {
            // 获取权限列表
            this.$store.dispatch('user/GetAuthority').then((res) => {
                // console.log(res)
                if (res.code == 200) {
                    var newData = JSON.parse(JSON.stringify(res.data))
                    res.data.unshift({
                        code: '21000',
                        describe: '全选',
                        remarks: '',
                        children: [],
                        pcode: '0'
                    })
                    // res.data = res.data.filter(item => {
                    //     return item.code != 11000
                    // })
                    this.option.data = res.data
                    // 根据对应角色返回对应角色权限
                    this.$store.dispatch('system/GetSysrolesDetail', {roleId: roleId}).then(res => {
                        // console.log(res)
                        if (res.code == 200) {
                            // 数据递归处理
                            this.option.data.forEach((item, index) => {
                                if (item.children && item.children.length > 0) {
                                    item.children.forEach((child, j) => {
                                        this.$set(this.option.data[index].children[j], 'edit', false)
                                        this.$set(this.option.data[index].children[j], 'view', false)
                                        res.data.authority.forEach((auth, i) => {
                                            if (child.code == auth.code) {
                                                this.$set(this.option.data[index].children[j], 'permissions', auth.permissions)
                                                this.$set(this.option.data[index].children[j], 'edit', auth.permissions.indexOf('edit') >= 0)
                                                this.$set(this.option.data[index].children[j], 'view', auth.permissions.indexOf('view') >= 0)
                                            }
                                        })
                                    })
                                } else {
                                    this.$set(this.option.data[index], 'edit', false)
                                    this.$set(this.option.data[index], 'view', false)
                                    res.data.authority.forEach((auth, i) => {
                                        if (item.code == auth.code) {
                                            this.$set(this.option.data[index], 'permissions', auth.permissions)
                                            this.$set(this.option.data[index], 'edit', auth.permissions.indexOf('edit') >= 0)
                                            this.$set(this.option.data[index], 'view', auth.permissions.indexOf('view') >= 0)
                                        }
                                    })
                                }
                            })
                            // 判断是否有edit全选
                            var check = true
                            this.$nextTick(() => {
                                this.option.data.forEach(ele => {
                                    if (ele.code != 20000 && ele.code != 21000) {
                                        if (ele.children.length > 0) {
                                            ele.children.forEach(child => {
                                                if (!child.edit) {
                                                    check = false
                                                }
                                            })
                                        } else {
                                            if (!ele.edit) {
                                                check = false
                                            }
                                        }
                                    }
                                })
                                if (check) {
                                    this.option.data.forEach(ele => {
                                        if (ele.code == 21000) {
                                            this.$set(ele, 'edit', true)
                                        }
                                    })
                                }
                            })
                            // 联动的判断view是否全选
                            var check1 = true
                            this.$nextTick(() => {
                                this.option.data.forEach(ele => {
                                    if (ele.code != 21000) {
                                        if (ele.children.length > 0) {
                                            ele.children.forEach(child => {
                                                if (!child.view) {
                                                    check1 = false
                                                }
                                            })
                                        } else {
                                            if (!ele.view) {
                                                check1 = false
                                            }
                                        }
                                    }
                                })
                                if (check1) {
                                    this.option.data.forEach(ele => {
                                        if (ele.code == 21000) {
                                            this.$set(ele, 'view', true)
                                        }
                                    })
                                }
                            })
                        } else {
                            console.log(res.msg)
                        }
                    })
                }
            })
        },
        editChange (row) {
            console.log('editChange', row, this.option)
            // 判断是否是首页，不是则edit控制住view
            if (row.code == 21000) {
                this.option.data.forEach(ele => {
                    if (row.edit) {
                        this.$set(ele, 'view', true)
                        this.$set(ele, 'edit', true)
                        if (ele.children.length > 0) {
                            ele.children.forEach(child => {
                                if (child.code != 20010 && child.code != 20020) {
                                    this.$set(child, 'view', true)
                                    this.$set(child, 'edit', true)
                                } else {
                                    this.$set(child, 'view', true)
                                }
                            })
                        }
                    } else {
                        this.$set(ele, 'edit', false)
                        if (ele.children.length > 0 && ele.code != 20000) {
                            ele.children.forEach(child => {
                                this.$set(child, 'edit', false)
                            })
                        }
                    }
                })
            } else {
                if (!row.edit) {
                    this.option.data.forEach(ele => {
                        if (ele.code == 21000) {
                            this.$set(ele, 'edit', false)
                        }
                    })
                } else {
                    this.$set(row, 'view', true)
                    // 判断edit是否全选
                    var check = true
                    this.$nextTick(() => {
                        this.option.data.forEach(ele => {
                            // if (ele.code != 11000 && ele.code != 20000 && ele.code != 21000) {
                            if (ele.code != 20000 && ele.code != 21000) {
                                if (ele.children.length > 0) {
                                    ele.children.forEach(child => {
                                        if (!child.edit) {
                                            check = false
                                        }
                                    })
                                } else {
                                    if (!ele.edit) {
                                        check = false
                                    }
                                }
                            }
                        })
                        if (check) {
                            this.option.data.forEach(ele => {
                                if (ele.code == 21000) {
                                    this.$set(ele, 'edit', true)
                                }
                            })
                        }
                    })
                    // 联动的判断view是否全选
                    var check1 = true
                    this.$nextTick(() => {
                        this.option.data.forEach(ele => {
                            // if (ele.code != 11000 && ele.code != 21000) {
                            if (ele.code != 21000) {
                                if (ele.children.length > 0) {
                                    ele.children.forEach(child => {
                                        if (!child.view) {
                                            check1 = false
                                        }
                                    })
                                } else {
                                    if (!ele.view) {
                                        check1 = false
                                    }
                                }
                            }
                        })
                        if (check1) {
                            this.option.data.forEach(ele => {
                                if (ele.code == 21000) {
                                    this.$set(ele, 'view', true)
                                }
                            })
                        }
                    })
                }
            }
        },
        viewChange (row) {
            console.log('viewChange', row, this.option)
            if (row.code == 21000) {
                this.option.data.forEach(ele => {
                    if (row.view) {
                        // this.$set(ele, 'edit', true)
                        this.$set(ele, 'view', true)
                        if (ele.children.length > 0) {
                            ele.children.forEach(child => {
                                this.$set(child, 'view', true)
                            })
                        }
                    } else {
                        this.$set(ele, 'edit', false)
                        this.$set(ele, 'view', false)
                        if (ele.children.length > 0) {
                            ele.children.forEach(child => {
                                this.$set(child, 'edit', false)
                                this.$set(child, 'view', false)
                            })
                        }
                    }
                })
            } else {
                if (!row.view) {
                    this.$set(row, 'edit', false)
                    this.option.data.forEach(ele => {
                        if (ele.code == 21000) {
                            this.$set(ele, 'view', false)
                            this.$set(ele, 'edit', false)
                        }
                    })
                } else {
                    // 检测查看权限是否全选
                    this.$set(row, 'view', true)
                    var check = true
                    this.$nextTick(() => {
                        this.option.data.forEach(ele => {
                            // if (ele.code != 11000 && ele.code != 21000) {
                            if (ele.code != 21000) {
                                if (ele.children.length > 0) {
                                    ele.children.forEach(child => {
                                        if (!child.view) {
                                            check = false
                                        }
                                    })
                                } else {
                                    if (!ele.view) {
                                        check = false
                                    }
                                }
                            }
                            console.log(check)
                        })
                        console.log(1, check)
                        if (check) {
                            this.option.data.forEach(ele => {
                                if (ele.code == 21000) {
                                    this.$set(ele, 'view', true)
                                }
                            })
                        }
                    })
                }
            }
        },
        // 是否显示父级互选框
        checkScope (row) {
            if (row.children && row.children.length === 0) {
                return true
            } else {
                return false
            }
        },
        // 触发事件
        handleClose () {
            this.$refs['ruleForm'].clearValidate()
            // this.$refs['ruleForm'].resetFields()
            this.$emit('handleClose')
        },
        closeDialog () {
            this.$refs['ruleForm'].clearValidate()
            // this.$refs['ruleForm'].resetFields()
            this.$emit('closeDialog')
        },
        confirmDialog () {
            // 扁平化树数组
            function mapData (arr) {
                var newArr = []
                arr.map((item) => {
                    var arr = []
                    if (item.view) {
                        arr.push('view')
                    }
                    if (item.edit) {
                        arr.push('edit')
                    }
                    var permissions = arr.join(',')
                    if (item.children && item.children.length > 0) {
                        newArr.push({
                            code: item.code,
                            permissions: ''
                        })
                        newArr = newArr.concat(mapData(item.children))
                    } else {
                        newArr.push({
                            code: item.code,
                            permissions: permissions
                        })
                    }
                })
                return newArr
            }
            console.log(111)
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    var authority = mapData(this.option.data)
                    var newAuthority = []
                    authority.forEach((item, index) => {
                        if (item.code != 21000) {
                            if (item.permissions != '') {
                                newAuthority.push(item)
                            }
                        }
                    })
                    console.log(authority)
                    console.log(newAuthority)
                    // return
                    var params = {
                        name: this.ruleForm.name,
                        phone: this.ruleForm.phone,
                        roleId: this.ruleForm.roleId,
                        state: this.ruleForm.state,
                        password: this.ruleForm.password,
                        authority: newAuthority,
                        underCustId: this.ruleForm.underCustId
                    }
                    params.userId = this.$parent.userId
                    this.dialogLoading = true
                    this.$store.dispatch('system/EditSysuser', params).then(res => {
                        // console.log(res)
                        if (res.code == 200) {
                            this.$message({
                                message: res.msg,
                                duration: 2000,
                                type: 'success'
                            })
                            this.$emit('confirmDialog')
                        } else {
                            this.$message({
                                message: res.msg,
                                duration: 2000,
                                type: 'error'
                            })
                            this.dialogLoading = false
                        }
                    }).catch(err => {
                        console.log(err)
                        this.dialogLoading = false
                    })
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        // 获取详情
        getDetail () {
            this.option.data = []
            this.dialogLoading = false
            // 获取角色列表
            this.$store.dispatch('system/GetSysroles').then(res => {
                if (res.code == 200) {
                    this.roleType = res.data
                } else {
                    console.log(res.msg)
                }
            })
            // 初始话编辑数据
            // this.ruleForm = this.$parent.rowData
            this.ruleForm = JSON.parse(JSON.stringify(this.$parent.rowData))
            this.ruleForm.roleId = this.ruleForm.roleId + ''
            // 状态状态
            this.ruleForm.state = this.ruleForm.state % 10
            // 获取权限列表
            this.$store.dispatch('user/GetAuthority').then((res) => {
                if (res.code == 200) {
                    res.data.unshift({
                        code: '21000',
                        describe: '全选',
                        remarks: '',
                        children: [],
                        pcode: '0'
                    })
                    this.option.data = res.data
                    console.log(res.data)
                    // 获取当前用户权限
                    this.$store.dispatch('system/GetUserAuth', {userId: this.ruleForm.userId}).then(res => {
                        if (res.code == 200) {
                            this.option.data.forEach((item, index) => {
                                if (item.children && item.children.length > 0) {
                                    item.children.forEach((child, j) => {
                                        res.data.forEach((auth, i) => {
                                            if (child.code == auth.code) {
                                                this.$set(this.option.data[index].children[j], 'permissions', auth.permissions)
                                                this.$set(this.option.data[index].children[j], 'edit', auth.permissions.indexOf('edit') >= 0)
                                                this.$set(this.option.data[index].children[j], 'view', auth.permissions.indexOf('view') >= 0)
                                            }
                                        })
                                    })
                                } else {
                                    res.data.forEach((auth, i) => {
                                        if (item.code == auth.code) {
                                            this.$set(this.option.data[index], 'permissions', auth.permissions)
                                            this.$set(this.option.data[index], 'edit', auth.permissions.indexOf('edit') >= 0)
                                            this.$set(this.option.data[index], 'view', auth.permissions.indexOf('view') >= 0)
                                        }
                                    })
                                }
                            })
                            console.log(this.option.data)
                            // 判断是否有edit全选
                            var check = true
                            this.$nextTick(() => {
                                console.log(this.option.data)
                                this.option.data.forEach(ele => {
                                    if (ele.code != 20000 && ele.code != 21000) {
                                        if (ele.children.length > 0) {
                                            ele.children.forEach(child => {
                                                if (!child.edit) {
                                                    check = false
                                                }
                                            })
                                        } else {
                                            if (!ele.edit) {
                                                check = false
                                            }
                                        }
                                    }
                                    console.log(check)
                                })
                                if (check) {
                                    // console.log(111)
                                    this.option.data.forEach(ele => {
                                        if (ele.code == 21000) {
                                            this.$set(ele, 'edit', true)
                                        }
                                    })
                                }
                            })
                            // 联动的判断view是否全选
                            var check1 = true
                            this.$nextTick(() => {
                                this.option.data.forEach(ele => {
                                    if (ele.code != 21000) {
                                        if (ele.children.length > 0) {
                                            ele.children.forEach(child => {
                                                if (!child.view) {
                                                    check1 = false
                                                }
                                            })
                                        } else {
                                            if (!ele.view) {
                                                check1 = false
                                            }
                                        }
                                    }
                                })
                                if (check1) {
                                    this.option.data.forEach(ele => {
                                        if (ele.code == 21000) {
                                            this.$set(ele, 'view', true)
                                        }
                                    })
                                }
                            })
                        } else {
                            console.log(res.msg)
                        }
                    })
                }
            })
            this.getUnderAgentUser()
        }
    }
}
</script>
<style lang="scss" scoped>
.select-width{
    width: 100%;
}
.index-edit{
    .dialog-body{
        height: 400px;
        overflow: auto;
    }
}
</style>
